<template>
  <el-breadcrumb separator="/" class="breadcrumb">
    <el-breadcrumb-item
      v-for="(item, index) in breadcrumbs"
      :key="`breadcrumb-${item.path}-${index}`"
      :to="index === breadcrumbs.length - 1 ? '' : { path: item.path }"
    >
      {{ item.meta?.title }}
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import type { RouteLocationMatched } from 'vue-router'

// 面包屑项类型
interface BreadcrumbItem {
  path: string
  meta?: {
    title?: string
  }
}

const route = useRoute()
const breadcrumbs = ref<(RouteLocationMatched | BreadcrumbItem)[]>([])

// 生成面包屑
const getBreadcrumb = async () => {
  try {
    // 过滤掉不需要显示在面包屑中的路由
    let matched: (RouteLocationMatched | BreadcrumbItem)[] = route.matched.filter(item => item.meta && item.meta.title)
    
    // 如果第一个不是首页，添加首页
    const first = matched[0]
    if (!first || (first as RouteLocationMatched).name !== 'Dashboard') {
      const homeItem: BreadcrumbItem = { path: '/dashboard', meta: { title: '首页' } }
      matched = [homeItem].concat(matched)
    }
    
    const newBreadcrumbs = matched.filter((item, index, arr) => {
      // 去重
      return arr.findIndex(route => route.path === item.path) === index
    })
    
    // 使用 nextTick 确保 DOM 更新完成
    await nextTick()
    breadcrumbs.value = newBreadcrumbs
  } catch (error) {
    console.warn('生成面包屑时出错:', error)
    // 设置默认面包屑
    const homeItem: BreadcrumbItem = { path: '/dashboard', meta: { title: '首页' } }
    breadcrumbs.value = [homeItem]
  }
}

// 监听路由变化
watch(route, getBreadcrumb, { immediate: true })
</script>

<style scoped>
.breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
}

.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.5s;
}

.breadcrumb-enter-from,
.breadcrumb-leave-active {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-move {
  transition: all 0.5s;
}

.breadcrumb-leave-active {
  position: absolute;
}
</style>